<?php
/**
 * @author Jumper
 * date: 2021/04/15
 */
declare(strict_types=1);
namespace App\Controller;

use Hyperf\Contract\{OnOpenInterface, OnCloseInterface, OnMessageInterface};
use Psr\Container\ContainerInterface;
use Swoole\Server;
use Swoole\WebSocket\Server as WebSocketServer;
use Swoole\WebSocket\Frame;
use Swoole\Http\Request;

use App\Chat\Core\Packet;
use App\Chat\Core\Room;
use App\Log;

class WebSocketController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    /**
     * @var Room
     */
    private $room;
    
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->room = new Room(redis());
    }
    
    public function onMessage($server, Frame $frame) : void
    {
        $data = Packet::decode($frame->data);
        if (!isset($data['code']) && $data['code'] != ErrorCode::SUCCESS) {
            Log::info('data error');
            Log::info($data);
            return;
        }

        $this->room->exec($server, $frame->fd, $data['data']);
    }

    public function onOpen($server, Request $request) : void 
    {
        Log::info('fd:' . $request->fd . ' connected');
    }

    public function onClose($server, int $fd, int $reactorId) : void 
    {
        Log::info('fd:' . $fd . ' leaved');
        $this->room->exec($server, $fd, [
            'method' => Room::USER_LEAVE,
        ]);
    }
}